# Copyright (c) 2009 by Alex Leone <acleone ~at~ gmail.com>
#
# This file is part of epp.
#
# epp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# epp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with epp.  If not, see <http://www.gnu.org/licenses/>.

r"""
Contains the [if] tag.

Syntax:
    [if t="statement to be eval-ed" iftrue:]
        statements
    [/if t="statement to be eval-ed" tagname2:]
        (equivalent to else if)
    [/if else:]
        else
    [/if] (optional)

Examples:
    Note: s[1:] in p.parsetags(s[1:]) is to strip the leading '\n'
          from s

    >>> import epp
    >>> p = epp.Epp()
    >>> s = '''
    ... [define tag1=""]
    ... [if t="len('[tag1]') == 0" do:]
    ...  tag1 has no length
    ... [if t="5**2 == 25" do:]
    ...  5^2 is 25!
    ... [/if else:]
    ...  just kidding!'''
    >>> print(p.parsetags(s[1:]))
    tag1 has no length
    5^2 is 25!
"""

import tags
from tags.tag import Tag

tagnames = ["if"]

class If(Tag):

    def replace(self, eppinst, tagName, attrs):
        """
        If(not) defined.
        Returns: the result of parsing all the tags in the condition that
                is true.
        """
        if len(attrs) < 2:
            raise SyntaxError(
                    "[%s] needs `t='test' s:' - a test and statements"
                    % (tagName))
        for i in xrange(0, len(attrs), 2):
            testName, testValue = attrs[i]
            if testName == 'else':
                return eppinst.parsetags(testValue)
            if eval(eppinst.parsetags(testValue)):
                return eppinst.parsetags(attrs[i + 1][1])
        return ''